# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.template import Template

from wlapps.utils.common import get_theme


# 根据不同的主题设置调用不同的模板
def templates_for_theme(request, templates):
    if not isinstance(templates, (list, tuple)):
        templates = [templates]
    # 从配置中导入当前使用的主题
    theme = get_theme()
    theme_templates = []
    for template in templates:
        theme_templates.append("%s/%s" % (theme, template))
        if theme != "wltheme":
            theme_templates.append("wltheme/%s" % template)
        theme_templates.append(template)
    return theme_templates


class TemplateForThemeMiddleware(object):
    """根据不同的主题设置调用不同的模板的中间件，放在subhost中间件后面、device中间件前面"""

    def process_template_response(self, request, response):
        if hasattr(response, "template_name"):
            if not isinstance(response.template_name, Template):
                templates = templates_for_theme(request, response.template_name)
                response.template_name = templates
        return response
